"""
智能项目分析器

使用NLP技术理解用户意图，提取关键信息，生成结构化的编程任务。
"""

import re
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass
from enum import Enum


class ProjectType(Enum):
    """项目类型枚举"""
    SINGLE_PAGE = "single_page"  # 单页面应用
    MULTI_FILE = "multi_file"    # 多文件项目
    WEB_APP = "web_app"         # Web应用
    DESKTOP_APP = "desktop_app"  # 桌面应用
    MOBILE_APP = "mobile_app"    # 移动应用
    API_SERVICE = "api_service"  # API服务
    LIBRARY = "library"         # 库/包
    GAME = "game"              # 游戏
    SCRIPT = "script"          # 脚本
    UNKNOWN = "unknown"        # 未知类型


class Complexity(Enum):
    """项目复杂度"""
    SIMPLE = "simple"      # 简单
    MEDIUM = "medium"      # 中等
    COMPLEX = "complex"    # 复杂


@dataclass
class ProjectInfo:
    """项目信息数据类"""
    project_type: ProjectType
    complexity: Complexity
    languages: List[str]
    frameworks: List[str]
    features: List[str]
    target_platform: str
    description: str
    estimated_files: int
    suggested_structure: Dict[str, Any]


class IntentAnalyzer:
    """意图分析器"""
    
    def __init__(self):
        # 项目类型关键词映射
        self.project_type_keywords = {
            ProjectType.SINGLE_PAGE: [
                "单页", "单文件", "一个文件", "简单页面", "静态页面", "计算器", "页面",
                "single page", "one file", "simple page", "static page", "calculator", "page"
            ],
            ProjectType.WEB_APP: [
                "网站", "网页", "web应用", "web app", "网站应用", 
                "web application", "网站", "网页应用"
            ],
            ProjectType.DESKTOP_APP: [
                "桌面应用", "桌面程序", "桌面软件", "GUI应用", 
                "desktop app", "desktop application", "GUI application"
            ],
            ProjectType.MOBILE_APP: [
                "手机应用", "移动应用", "app", "手机app", 
                "mobile app", "mobile application", "手机程序"
            ],
            ProjectType.API_SERVICE: [
                "API", "接口", "服务", "后端", "server", 
                "api service", "backend", "微服务"
            ],
            ProjectType.LIBRARY: [
                "库", "包", "模块", "library", "package", 
                "module", "工具包", "SDK"
            ],
            ProjectType.GAME: [
                "游戏", "game", "小游戏", "游戏应用", 
                "game app", "游戏程序"
            ],
            ProjectType.SCRIPT: [
                "脚本", "script", "工具", "自动化", 
                "tool", "automation", "批处理"
            ]
        }
        
        # 编程语言关键词映射
        self.language_keywords = {
            "javascript": ["javascript", "js", "前端", "网页", "浏览器", "计算器", "页面"],
            "typescript": ["typescript", "ts", "类型安全"],
            "python": ["python", "py", "爬虫", "数据分析", "机器学习"],
            "java": ["java", "企业级", "spring", "android"],
            "cpp": ["c++", "cpp", "c plus plus", "系统编程"],
            "csharp": ["c#", "csharp", "dotnet", ".net"],
            "go": ["go", "golang", "微服务", "云原生"],
            "rust": ["rust", "系统编程", "性能"],
            "php": ["php", "web开发", "后端"],
            "ruby": ["ruby", "rails", "web框架"],
            "swift": ["swift", "ios", "苹果"],
            "kotlin": ["kotlin", "android", "移动开发"],
            "html": ["html", "网页", "标记语言", "页面"],
            "css": ["css", "样式", "美化"],
            "sql": ["sql", "数据库", "查询"]
        }
        
        # 框架关键词映射
        self.framework_keywords = {
            "react": ["react", "reactjs", "前端框架"],
            "vue": ["vue", "vuejs", "前端框架"],
            "angular": ["angular", "前端框架"],
            "express": ["express", "nodejs", "后端框架"],
            "django": ["django", "python框架"],
            "flask": ["flask", "python框架"],
            "spring": ["spring", "java框架"],
            "fastapi": ["fastapi", "python api"],
            "laravel": ["laravel", "php框架"],
            "rails": ["rails", "ruby框架"],
            "bootstrap": ["bootstrap", "css框架"],
            "tailwind": ["tailwind", "css框架"],
            "jquery": ["jquery", "js库"],
            "three.js": ["three.js", "3d", "webgl"],
            "phaser": ["phaser", "游戏引擎"],
            "electron": ["electron", "桌面应用"],
            "react-native": ["react-native", "移动开发"],
            "flutter": ["flutter", "移动开发"],
            "unity": ["unity", "游戏引擎"],
            "godot": ["godot", "游戏引擎"]
        }
        
        # 功能特性关键词映射
        self.feature_keywords = {
            "用户认证": ["登录", "注册", "认证", "auth", "用户管理"],
            "数据库": ["数据库", "db", "存储", "数据持久化"],
            "API接口": ["api", "接口", "rest", "graphql"],
            "实时通信": ["实时", "websocket", "聊天", "推送"],
            "文件上传": ["上传", "文件", "图片", "upload"],
            "搜索功能": ["搜索", "查找", "search", "过滤"],
            "支付功能": ["支付", "付款", "payment", "订单"],
            "地图功能": ["地图", "定位", "gps", "地理位置"],
            "游戏功能": ["游戏", "得分", "关卡", "碰撞检测"],
            "动画效果": ["动画", "过渡", "效果", "animation"],
            "响应式设计": ["响应式", "移动端", "适配", "responsive"],
            "PWA": ["pwa", "离线", "安装", "service worker"],
            "国际化": ["多语言", "i18n", "国际化", "本地化"],
            "主题切换": ["主题", "深色模式", "浅色模式", "dark mode"],
            "数据可视化": ["图表", "可视化", "dashboard", "统计"]
        }
        
        # 复杂度指示词
        self.complexity_indicators = {
            Complexity.SIMPLE: [
                "简单", "基础", "入门", "demo", "示例", "简单实现",
                "simple", "basic", "demo", "example", "tutorial"
            ],
            Complexity.COMPLEX: [
                "复杂", "高级", "企业级", "完整", "生产级", "专业",
                "complex", "advanced", "enterprise", "complete", "production"
            ]
        }
    
    def analyze_intent(self, user_input: str) -> ProjectInfo:
        """
        分析用户意图，提取项目信息
        
        Args:
            user_input: 用户输入的需求描述
            
        Returns:
            ProjectInfo: 分析后的项目信息
        """
        user_input_lower = user_input.lower()
        
        # 1. 分析项目类型
        project_type = self._analyze_project_type(user_input_lower)
        
        # 2. 分析编程语言
        languages = self._analyze_languages(user_input_lower)
        
        # 3. 分析框架
        frameworks = self._analyze_frameworks(user_input_lower)
        
        # 4. 分析功能特性
        features = self._analyze_features(user_input_lower)
        
        # 5. 分析目标平台
        target_platform = self._analyze_target_platform(user_input_lower)
        
        # 6. 分析复杂度
        complexity = self._analyze_complexity(user_input_lower)
        
        # 7. 估算文件数量
        estimated_files = self._estimate_file_count(project_type, complexity, features)
        
        # 8. 生成建议的项目结构
        suggested_structure = self._generate_project_structure(
            project_type, languages, frameworks, features, complexity
        )
        
        return ProjectInfo(
            project_type=project_type,
            complexity=complexity,
            languages=languages,
            frameworks=frameworks,
            features=features,
            target_platform=target_platform,
            description=user_input,
            estimated_files=estimated_files,
            suggested_structure=suggested_structure
        )
    
    def _analyze_project_type(self, text: str) -> ProjectType:
        """分析项目类型"""
        # 特殊处理：游戏相关项目
        if any(keyword in text for keyword in ["游戏", "game", "贪吃蛇", "snake", "俄罗斯方块", "tetris"]):
            return ProjectType.GAME
        
        # 特殊处理：单页面项目
        if any(keyword in text for keyword in ["单页", "单文件", "一个文件", "简单页面"]):
            return ProjectType.SINGLE_PAGE
        
        # 根据关键词匹配项目类型
        for project_type, keywords in self.project_type_keywords.items():
            if any(keyword in text for keyword in keywords):
                return project_type
        
        # 默认根据语言推断
        if any(lang in text for lang in ["html", "css", "javascript", "js"]):
            return ProjectType.SINGLE_PAGE
        elif any(lang in text for lang in ["python", "java", "go", "rust"]):
            return ProjectType.API_SERVICE
        
        return ProjectType.UNKNOWN
    
    def _analyze_languages(self, text: str) -> List[str]:
        """分析编程语言"""
        detected_languages = []
        
        for language, keywords in self.language_keywords.items():
            if any(keyword in text for keyword in keywords):
                detected_languages.append(language)
        
        # 如果没有检测到语言，根据项目类型推断
        if not detected_languages:
            if "网页" in text or "web" in text or "前端" in text:
                detected_languages = ["html", "css", "javascript"]
            elif "后端" in text or "api" in text or "服务" in text:
                detected_languages = ["python"]
        
        return list(set(detected_languages))  # 去重
    
    def _analyze_frameworks(self, text: str) -> List[str]:
        """分析框架"""
        detected_frameworks = []
        
        for framework, keywords in self.framework_keywords.items():
            if any(keyword in text for keyword in keywords):
                detected_frameworks.append(framework)
        
        return list(set(detected_frameworks))
    
    def _analyze_features(self, text: str) -> List[str]:
        """分析功能特性"""
        detected_features = []
        
        for feature, keywords in self.feature_keywords.items():
            if any(keyword in text for keyword in keywords):
                detected_features.append(feature)
        
        return list(set(detected_features))
    
    def _analyze_target_platform(self, text: str) -> str:
        """分析目标平台"""
        if any(keyword in text for keyword in ["移动", "手机", "mobile", "android", "ios"]):
            return "mobile"
        elif any(keyword in text for keyword in ["桌面", "桌面应用", "desktop", "gui"]):
            return "desktop"
        elif any(keyword in text for keyword in ["网页", "web", "浏览器", "browser"]):
            return "web"
        elif any(keyword in text for keyword in ["服务器", "server", "云端", "cloud"]):
            return "server"
        else:
            return "web"  # 默认web平台
    
    def _analyze_complexity(self, text: str) -> Complexity:
        """分析项目复杂度"""
        # 检查复杂度指示词
        for complexity, keywords in self.complexity_indicators.items():
            if any(keyword in text for keyword in keywords):
                return complexity
        
        # 根据功能数量推断复杂度
        feature_count = len(self._analyze_features(text))
        if feature_count >= 5:
            return Complexity.COMPLEX
        elif feature_count >= 2:
            return Complexity.MEDIUM
        else:
            return Complexity.SIMPLE
    
    def _estimate_file_count(self, project_type: ProjectType, complexity: Complexity, features: List[str]) -> int:
        """估算文件数量"""
        base_files = {
            ProjectType.SINGLE_PAGE: 1,
            ProjectType.MULTI_FILE: 3,
            ProjectType.WEB_APP: 5,
            ProjectType.DESKTOP_APP: 8,
            ProjectType.MOBILE_APP: 10,
            ProjectType.API_SERVICE: 6,
            ProjectType.LIBRARY: 4,
            ProjectType.GAME: 7,
            ProjectType.SCRIPT: 1,
            ProjectType.UNKNOWN: 3
        }
        
        complexity_multiplier = {
            Complexity.SIMPLE: 1.0,
            Complexity.MEDIUM: 1.5,
            Complexity.COMPLEX: 2.5
        }
        
        base_count = base_files.get(project_type, 3)
        multiplier = complexity_multiplier.get(complexity, 1.0)
        feature_bonus = len(features) * 0.5
        
        return int(base_count * multiplier + feature_bonus)
    
    def _generate_project_structure(self, project_type: ProjectType, languages: List[str], 
                                  frameworks: List[str], features: List[str], 
                                  complexity: Complexity) -> Dict[str, Any]:
        """生成建议的项目结构"""
        structure = {
            "type": project_type.value,
            "files": [],
            "directories": [],
            "dependencies": [],
            "build_tools": [],
            "deployment": []
        }
        
        if project_type == ProjectType.SINGLE_PAGE:
            structure["files"] = ["index.html"]
            if "css" in languages:
                structure["files"].append("style.css")
            if "javascript" in languages:
                structure["files"].append("script.js")
        
        elif project_type == ProjectType.GAME:
            structure["files"] = ["index.html", "game.js", "style.css"]
            structure["directories"] = ["assets/", "assets/images/", "assets/sounds/"]
            if "phaser" in frameworks:
                structure["dependencies"].append("phaser")
        
        elif project_type == ProjectType.WEB_APP:
            structure["files"] = ["index.html", "app.js", "style.css"]
            structure["directories"] = ["src/", "public/", "assets/"]
            if "react" in frameworks:
                structure["dependencies"].append("react")
                structure["build_tools"].append("webpack")
            if "vue" in frameworks:
                structure["dependencies"].append("vue")
                structure["build_tools"].append("vite")
        
        elif project_type == ProjectType.API_SERVICE:
            structure["files"] = ["main.py", "requirements.txt", "README.md"]
            structure["directories"] = ["src/", "tests/", "docs/"]
            if "fastapi" in frameworks:
                structure["dependencies"].append("fastapi")
                structure["dependencies"].append("uvicorn")
            if "数据库" in features:
                structure["dependencies"].append("sqlalchemy")
        
        return structure


class TaskGenerator:
    """结构化编程任务生成器"""
    
    def __init__(self):
        self.task_templates = {
            ProjectType.SINGLE_PAGE: self._generate_single_page_tasks,
            ProjectType.GAME: self._generate_game_tasks,
            ProjectType.WEB_APP: self._generate_web_app_tasks,
            ProjectType.API_SERVICE: self._generate_api_tasks,
            ProjectType.DESKTOP_APP: self._generate_desktop_app_tasks,
            ProjectType.MOBILE_APP: self._generate_mobile_app_tasks,
            ProjectType.LIBRARY: self._generate_library_tasks,
            ProjectType.SCRIPT: self._generate_script_tasks
        }
    
    def generate_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """
        生成结构化的编程任务
        
        Args:
            project_info: 项目信息
            
        Returns:
            List[Dict]: 任务列表
        """
        generator = self.task_templates.get(project_info.project_type, self._generate_generic_tasks)
        return generator(project_info)
    
    def _generate_single_page_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成单页面项目任务"""
        tasks = []
        
        # 基础HTML结构
        tasks.append({
            "id": "create_html_structure",
            "title": "创建HTML基础结构",
            "description": "创建包含基本HTML5结构的index.html文件",
            "priority": "high",
            "estimated_time": "10分钟",
            "files": ["index.html"],
            "dependencies": []
        })
        
        # CSS样式
        if "css" in project_info.languages:
            tasks.append({
                "id": "create_css_styles",
                "title": "创建CSS样式文件",
                "description": "创建style.css文件，实现页面样式和布局",
                "priority": "high",
                "estimated_time": "20分钟",
                "files": ["style.css"],
                "dependencies": ["create_html_structure"]
            })
        
        # JavaScript功能
        if "javascript" in project_info.languages:
            tasks.append({
                "id": "implement_javascript",
                "title": "实现JavaScript功能",
                "description": "创建script.js文件，实现页面交互功能",
                "priority": "high",
                "estimated_time": "30分钟",
                "files": ["script.js"],
                "dependencies": ["create_html_structure"]
            })
        
        # 特殊功能任务
        for feature in project_info.features:
            if feature == "游戏功能":
                tasks.append({
                    "id": "implement_game_logic",
                    "title": "实现游戏逻辑",
                    "description": "实现游戏核心逻辑，包括游戏状态管理和用户交互",
                    "priority": "high",
                    "estimated_time": "45分钟",
                    "files": ["script.js"],
                    "dependencies": ["implement_javascript"]
                })
        
        return tasks
    
    def _generate_game_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成游戏项目任务"""
        tasks = []
        
        # 基础文件结构
        tasks.extend([
            {
                "id": "create_html_canvas",
                "title": "创建HTML画布",
                "description": "创建包含canvas元素的HTML文件",
                "priority": "high",
                "estimated_time": "5分钟",
                "files": ["index.html"],
                "dependencies": []
            },
            {
                "id": "setup_game_canvas",
                "title": "设置游戏画布",
                "description": "配置canvas元素和基础游戏环境",
                "priority": "high",
                "estimated_time": "15分钟",
                "files": ["game.js"],
                "dependencies": ["create_html_canvas"]
            },
            {
                "id": "implement_game_loop",
                "title": "实现游戏循环",
                "description": "创建游戏主循环，处理帧更新和渲染",
                "priority": "high",
                "estimated_time": "20分钟",
                "files": ["game.js"],
                "dependencies": ["setup_game_canvas"]
            },
            {
                "id": "implement_game_objects",
                "title": "实现游戏对象",
                "description": "创建游戏中的各种对象类（如蛇、食物等）",
                "priority": "medium",
                "estimated_time": "30分钟",
                "files": ["game.js"],
                "dependencies": ["implement_game_loop"]
            },
            {
                "id": "implement_controls",
                "title": "实现游戏控制",
                "description": "添加键盘控制和游戏交互逻辑",
                "priority": "medium",
                "estimated_time": "20分钟",
                "files": ["game.js"],
                "dependencies": ["implement_game_objects"]
            },
            {
                "id": "add_game_styles",
                "title": "添加游戏样式",
                "description": "创建CSS文件，美化游戏界面",
                "priority": "low",
                "estimated_time": "15分钟",
                "files": ["style.css"],
                "dependencies": ["create_html_canvas"]
            }
        ])
        
        return tasks
    
    def _generate_web_app_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成Web应用任务"""
        tasks = []
        
        # 基础结构
        tasks.extend([
            {
                "id": "setup_project_structure",
                "title": "设置项目结构",
                "description": "创建项目目录结构和基础文件",
                "priority": "high",
                "estimated_time": "10分钟",
                "files": ["index.html", "src/", "public/"],
                "dependencies": []
            },
            {
                "id": "create_main_html",
                "title": "创建主HTML文件",
                "description": "创建应用的入口HTML文件",
                "priority": "high",
                "estimated_time": "15分钟",
                "files": ["index.html"],
                "dependencies": ["setup_project_structure"]
            }
        ])
        
        # 根据框架添加任务
        if "react" in project_info.frameworks:
            tasks.append({
                "id": "setup_react_components",
                "title": "设置React组件",
                "description": "创建React组件结构和基础组件",
                "priority": "high",
                "estimated_time": "30分钟",
                "files": ["src/App.js", "src/components/"],
                "dependencies": ["create_main_html"]
            })
        
        return tasks
    
    def _generate_api_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成API服务任务"""
        tasks = []
        
        tasks.extend([
            {
                "id": "setup_api_structure",
                "title": "设置API项目结构",
                "description": "创建API项目的目录结构和基础文件",
                "priority": "high",
                "estimated_time": "10分钟",
                "files": ["main.py", "requirements.txt"],
                "dependencies": []
            },
            {
                "id": "implement_main_api",
                "title": "实现主API文件",
                "description": "创建API的主入口文件和基础路由",
                "priority": "high",
                "estimated_time": "25分钟",
                "files": ["main.py"],
                "dependencies": ["setup_api_structure"]
            }
        ])
        
        if "数据库" in project_info.features:
            tasks.append({
                "id": "setup_database",
                "title": "设置数据库",
                "description": "配置数据库连接和模型",
                "priority": "medium",
                "estimated_time": "20分钟",
                "files": ["database.py", "models.py"],
                "dependencies": ["implement_main_api"]
            })
        
        return tasks
    
    def _generate_desktop_app_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成桌面应用任务"""
        return self._generate_generic_tasks(project_info)
    
    def _generate_mobile_app_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成移动应用任务"""
        return self._generate_generic_tasks(project_info)
    
    def _generate_library_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成库项目任务"""
        return self._generate_generic_tasks(project_info)
    
    def _generate_script_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成脚本任务"""
        return self._generate_generic_tasks(project_info)
    
    def _generate_generic_tasks(self, project_info: ProjectInfo) -> List[Dict[str, Any]]:
        """生成通用任务"""
        return [
            {
                "id": "create_main_file",
                "title": "创建主文件",
                "description": "创建项目的主要文件",
                "priority": "high",
                "estimated_time": "20分钟",
                "files": ["main.py"],
                "dependencies": []
            }
        ]


class ProjectAnalyzer:
    """项目分析器主类"""
    
    def __init__(self):
        self.intent_analyzer = IntentAnalyzer()
        self.task_generator = TaskGenerator()
    
    def analyze_and_generate_tasks(self, user_input: str) -> Tuple[ProjectInfo, List[Dict[str, Any]]]:
        """
        分析用户输入并生成结构化任务
        
        Args:
            user_input: 用户输入的需求描述
            
        Returns:
            Tuple[ProjectInfo, List[Dict]]: 项目信息和任务列表
        """
        # 分析用户意图
        project_info = self.intent_analyzer.analyze_intent(user_input)
        
        # 生成结构化任务
        tasks = self.task_generator.generate_tasks(project_info)
        
        return project_info, tasks
    
    def get_project_summary(self, project_info: ProjectInfo) -> str:
        """获取项目摘要"""
        summary = f"""
项目类型: {project_info.project_type.value}
复杂度: {project_info.complexity.value}
编程语言: {', '.join(project_info.languages)}
框架: {', '.join(project_info.frameworks) if project_info.frameworks else '无'}
功能特性: {', '.join(project_info.features) if project_info.features else '无'}
目标平台: {project_info.target_platform}
预计文件数: {project_info.estimated_files}
        """.strip()
        
        return summary
